import 'package:flutter/material.dart';
import '../../models/chat_model.dart';
import '../../models/follow_category_model.dart';
import '../../utils/cached_image_widget.dart';

class ChatHistoryPage extends StatefulWidget {
  const ChatHistoryPage({super.key});

  @override
  State<ChatHistoryPage> createState() => _ChatHistoryPageState();
}

class _ChatHistoryPageState extends State<ChatHistoryPage> {
  int _selectedIndex = 0;
  String _selectedCategory = '全部';

  // 模拟关注分类数据
  final List<FollowCategory> _followCategories = [
    FollowCategory(
        id: '1',
        name: '家人',
        color: '#FF6B6B',
        isDefault: true,
        createdAt: DateTime.now()),
    FollowCategory(
        id: '2',
        name: '同事',
        color: '#4ECDC4',
        isDefault: true,
        createdAt: DateTime.now()),
    FollowCategory(
        id: '3',
        name: '高人',
        color: '#45B7D1',
        isDefault: true,
        createdAt: DateTime.now()),
    FollowCategory(
        id: '4',
        name: '朋友',
        color: '#96CEB4',
        isDefault: true,
        createdAt: DateTime.now()),
    FollowCategory(
        id: '5',
        name: '客户',
        color: '#FFEAA7',
        isDefault: true,
        createdAt: DateTime.now()),
  ];

  // 模拟聊天会话数据
  final List<ChatSession> _chatSessions = [
    ChatSession(
      id: '1',
      userId: 'current_user',
      otherUserId: '101',
      otherUsername: '妈妈',
      otherUserAvatar: '',
      lastMessage: '今天记得按时吃饭哦',
      lastMessageTime: DateTime.now().subtract(const Duration(minutes: 30)),
      unreadCount: 2,
      isOnline: true,
      categoryId: '1',
    ),
    ChatSession(
      id: '2',
      userId: 'current_user',
      otherUserId: '201',
      otherUsername: '张经理',
      otherUserAvatar: '',
      lastMessage: '项目进度如何？',
      lastMessageTime: DateTime.now().subtract(const Duration(hours: 2)),
      unreadCount: 0,
      isOnline: false,
      categoryId: '2',
    ),
    ChatSession(
      id: '3',
      userId: 'current_user',
      otherUserId: '301',
      otherUsername: '王专家',
      otherUserAvatar: '',
      lastMessage: '技术方案已经发给你了',
      lastMessageTime: DateTime.now().subtract(const Duration(hours: 5)),
      unreadCount: 1,
      isOnline: true,
      categoryId: '3',
    ),
    ChatSession(
      id: '4',
      userId: 'current_user',
      otherUserId: '401',
      otherUsername: '小明',
      otherUserAvatar: '',
      lastMessage: '周末一起打球吗？',
      lastMessageTime: DateTime.now().subtract(const Duration(days: 1)),
      unreadCount: 0,
      isOnline: false,
      categoryId: '4',
    ),
    ChatSession(
      id: '5',
      userId: 'current_user',
      otherUserId: '501',
      otherUsername: '客户A',
      otherUserAvatar: '',
      lastMessage: '合同已经确认，谢谢',
      lastMessageTime: DateTime.now().subtract(const Duration(days: 2)),
      unreadCount: 0,
      isOnline: false,
      categoryId: '5',
    ),
  ];

  // 模拟聊天消息数据
  final Map<String, List<ChatMessage>> _chatMessages = {
    '1': [
      ChatMessage(
        id: '1',
        senderId: 'current_user',
        receiverId: '101',
        content: '妈妈，我今天加班',
        type: MessageType.text,
        timestamp: DateTime.now().subtract(const Duration(hours: 2)),
        isRead: true,
      ),
      ChatMessage(
        id: '2',
        senderId: '101',
        receiverId: 'current_user',
        content: '好的，记得按时吃饭哦',
        type: MessageType.text,
        timestamp: DateTime.now().subtract(const Duration(minutes: 30)),
        isRead: false,
      ),
      ChatMessage(
        id: '3',
        senderId: '101',
        receiverId: 'current_user',
        content: '我给你做了你爱吃的菜',
        type: MessageType.text,
        timestamp: DateTime.now().subtract(const Duration(minutes: 25)),
        isRead: false,
      ),
    ],
    '2': [
      ChatMessage(
        id: '4',
        senderId: '201',
        receiverId: 'current_user',
        content: '项目进度如何？',
        type: MessageType.text,
        timestamp: DateTime.now().subtract(const Duration(hours: 2)),
        isRead: true,
      ),
    ],
  };

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('聊天记录'),
        backgroundColor: Theme.of(context).primaryColor,
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            icon: const Icon(Icons.search),
            onPressed: () => _showSearchDialog(),
          ),
          IconButton(
            icon: const Icon(Icons.filter_list),
            onPressed: () => _showFilterDialog(),
          ),
        ],
      ),
      body: Column(
        children: [
          // 分类标签
          Container(
            height: 50,
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: _followCategories.length + 1,
              itemBuilder: (context, index) {
                if (index == 0) {
                  return _buildCategoryChip('全部', index == _selectedIndex, () {
                    setState(() {
                      _selectedIndex = 0;
                      _selectedCategory = '全部';
                    });
                  });
                }
                final category = _followCategories[index - 1];
                return _buildCategoryChip(
                  category.name,
                  index == _selectedIndex,
                  () {
                    setState(() {
                      _selectedIndex = index;
                      _selectedCategory = category.name;
                    });
                  },
                  color:
                      Color(int.parse(category.color.replaceAll('#', '0xFF'))),
                );
              },
            ),
          ),
          // 聊天会话列表
          Expanded(
            child: ListView.builder(
              padding: const EdgeInsets.all(16),
              itemCount: _getFilteredChatSessions().length,
              itemBuilder: (context, index) {
                final session = _getFilteredChatSessions()[index];
                return _buildChatSessionItem(session);
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCategoryChip(String label, bool isSelected, VoidCallback onTap,
      {Color? color}) {
    return Padding(
      padding: const EdgeInsets.only(right: 8),
      child: FilterChip(
        label: Text(
          label,
          style: TextStyle(
            color: isSelected ? Colors.white : Colors.black87,
            fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
          ),
        ),
        selected: isSelected,
        onSelected: (_) => onTap(),
        backgroundColor: Colors.grey[200],
        selectedColor: color ?? Theme.of(context).primaryColor,
        checkmarkColor: Colors.white,
      ),
    );
  }

  Widget _buildChatSessionItem(ChatSession session) {
    final category = _followCategories.firstWhere(
      (c) => c.id == session.categoryId,
      orElse: () => FollowCategory(
          id: '', name: '', color: '#000000', createdAt: DateTime.now()),
    );

    return Card(
      margin: const EdgeInsets.only(bottom: 8),
      child: ListTile(
        leading: Stack(
          children: [
            CachedAvatarWidget(
              avatarUrl: session.otherUserAvatar,
              size: 50,
            ),
            if (session.isOnline)
              Positioned(
                right: 0,
                bottom: 0,
                child: Container(
                  width: 12,
                  height: 12,
                  decoration: BoxDecoration(
                    color: Colors.green,
                    shape: BoxShape.circle,
                    border: Border.all(color: Colors.white, width: 2),
                  ),
                ),
              ),
          ],
        ),
        title: Row(
          children: [
            Text(
              session.otherUsername,
              style: const TextStyle(fontWeight: FontWeight.w500),
            ),
            const SizedBox(width: 8),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
              decoration: BoxDecoration(
                color: Color(int.parse(category.color.replaceAll('#', '0xFF')))
                    .withOpacity(0.2),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Text(
                category.name,
                style: TextStyle(
                  fontSize: 10,
                  color:
                      Color(int.parse(category.color.replaceAll('#', '0xFF'))),
                ),
              ),
            ),
          ],
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              session.lastMessage,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
            Text(
              _formatTime(session.lastMessageTime),
              style: const TextStyle(fontSize: 12, color: Colors.grey),
            ),
          ],
        ),
        trailing: session.unreadCount > 0
            ? Container(
                padding: const EdgeInsets.all(6),
                decoration: BoxDecoration(
                  color: Colors.red,
                  borderRadius: BorderRadius.circular(10),
                ),
                constraints: const BoxConstraints(
                  minWidth: 20,
                  minHeight: 20,
                ),
                child: Text(
                  session.unreadCount > 99
                      ? '99+'
                      : session.unreadCount.toString(),
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 12,
                    fontWeight: FontWeight.bold,
                  ),
                  textAlign: TextAlign.center,
                ),
              )
            : null,
        onTap: () => _showChatDetail(session),
      ),
    );
  }

  void _showChatDetail(ChatSession session) {
    final messages = _chatMessages[session.id] ?? [];

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (context) => Container(
        height: MediaQuery.of(context).size.height * 0.8,
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            // 头部
            Row(
              children: [
                CachedAvatarWidget(
                  avatarUrl: session.otherUserAvatar,
                  size: 40,
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        session.otherUsername,
                        style: const TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Text(
                        session.isOnline ? '在线' : '离线',
                        style: TextStyle(
                          fontSize: 14,
                          color: session.isOnline ? Colors.green : Colors.grey,
                        ),
                      ),
                    ],
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.close),
                  onPressed: () => Navigator.pop(context),
                ),
              ],
            ),
            const Divider(),
            // 消息列表
            Expanded(
              child: messages.isEmpty
                  ? const Center(
                      child: Text(
                        '暂无聊天记录',
                        style: TextStyle(color: Colors.grey),
                      ),
                    )
                  : ListView.builder(
                      itemCount: messages.length,
                      itemBuilder: (context, index) {
                        final message = messages[index];
                        final isMe = message.senderId == 'current_user';

                        return _buildMessageItem(message, isMe);
                      },
                    ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildMessageItem(ChatMessage message, bool isMe) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        mainAxisAlignment:
            isMe ? MainAxisAlignment.end : MainAxisAlignment.start,
        children: [
          if (!isMe) ...[
            CircleAvatar(
              backgroundColor: Colors.grey[300],
              radius: 15,
              child: const Icon(Icons.person, size: 18, color: Colors.grey),
            ),
            const SizedBox(width: 8),
          ],
          Flexible(
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              decoration: BoxDecoration(
                color: isMe ? Theme.of(context).primaryColor : Colors.grey[200],
                borderRadius: BorderRadius.circular(16),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    message.content,
                    style: TextStyle(
                      color: isMe ? Colors.white : Colors.black87,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    _formatTime(message.timestamp),
                    style: TextStyle(
                      fontSize: 10,
                      color: isMe ? Colors.white70 : Colors.grey,
                    ),
                  ),
                ],
              ),
            ),
          ),
          if (isMe) ...[
            const SizedBox(width: 8),
            CircleAvatar(
              backgroundColor: Colors.blue[100],
              radius: 15,
              child: const Icon(Icons.person, size: 18, color: Colors.blue),
            ),
          ],
        ],
      ),
    );
  }

  void _showSearchDialog() {
    final TextEditingController searchController = TextEditingController();

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('搜索聊天记录'),
        content: TextField(
          controller: searchController,
          decoration: const InputDecoration(
            labelText: '搜索关键词',
            hintText: '输入用户名或消息内容',
            border: OutlineInputBorder(),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              // 这里实现搜索功能
              Navigator.pop(context);
              _showSuccessMessage('搜索功能开发中...');
            },
            child: const Text('搜索'),
          ),
        ],
      ),
    );
  }

  void _showFilterDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('筛选聊天记录'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              title: const Text('按时间排序'),
              subtitle: const Text('最新消息在前'),
              trailing: const Icon(Icons.arrow_downward),
              onTap: () {
                Navigator.pop(context);
                _showSuccessMessage('已按时间排序');
              },
            ),
            ListTile(
              title: const Text('按未读消息'),
              subtitle: const Text('未读消息在前'),
              trailing: const Icon(Icons.mark_email_unread),
              onTap: () {
                Navigator.pop(context);
                _showSuccessMessage('已按未读消息排序');
              },
            ),
            ListTile(
              title: const Text('按在线状态'),
              subtitle: const Text('在线用户在前'),
              trailing: const Icon(Icons.circle),
              onTap: () {
                Navigator.pop(context);
                _showSuccessMessage('已按在线状态排序');
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  List<ChatSession> _getFilteredChatSessions() {
    if (_selectedCategory == '全部') {
      return _chatSessions;
    }
    final category = _followCategories.firstWhere(
      (c) => c.name == _selectedCategory,
      orElse: () => FollowCategory(
          id: '', name: '', color: '#000000', createdAt: DateTime.now()),
    );
    return _chatSessions
        .where((session) => session.categoryId == category.id)
        .toList();
  }

  String _formatTime(DateTime time) {
    final now = DateTime.now();
    final difference = now.difference(time);

    if (difference.inDays > 0) {
      return '${difference.inDays}天前';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }

  void _showSuccessMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.green,
        duration: const Duration(seconds: 2),
      ),
    );
  }
}
